<!-- 配送单详情 -->
<template>
    <div class="delivery-detail">
        <div v-if="showPage == 0" class="empty">
            <div v-if="detail.loading" style="position: fixed;top: 50%;left: 50%;transform: translate(-50%,-50%);">
                <van-loading type="spinner" />
            </div>
        </div>
        <div v-else-if="showPage == 1" class="unbound-tip">
            <div>您暂未绑定账户,</div>
            <div>请联系公司管理员扫码绑定！</div>
        </div>
        <div v-else-if="showPage == 2" class="unbound-tip">
            <div>您当前绑定多个账户,</div>
            <div>请联系公司管理员！</div>
        </div>

        <div v-else class="delivery-detail-container">
            <div v-if="detail.loading" style="position: fixed;top: 50%;left: 50%;transform: translate(-50%,-50%);">
                <van-loading type="spinner" />
            </div>
            <div v-else>
                <div class="common-box">
                    <div class="tag tag-0" v-if="detail.mainInfo.status == 0">未审核</div>
                    <div class="tag tag-1" v-if="detail.mainInfo.status == 1">已审核</div>
                    <div class="tag tag-0" v-if="detail.mainInfo.status == 2">驳回</div>
                    <div class="row-top">
                        <div class="left"><img src="@/assets/images/billno_icon.png"></div>
                        <div class="right">
                            <span class="billno">{{ detail.mainInfo.billno }}</span>
                            <span class="text">单号</span>
                        </div>
                    </div>
                    <div class="line"></div>
                    <div class="row">
                        <div class="left">目的港</div>
                        <div class="right"><span>{{ detail.mainInfo.portname }}</span></div>
                    </div>
                    <div class="row">
                        <div class="left">计划配送日期</div>
                        <div class="right"><span>{{ detail.mainInfo.plandate }}</span></div>
                    </div>
                    <div class="row">
                        <div class="left">配送方式</div>
                        <div class="right"><span>{{ detail.mainInfo.deliverytype === '0' ? '直送' :
                            detail.mainInfo.deliverytype === '1' ? '云仓' : '' }}</span></div>
                    </div>
                    <div class="row">
                        <div class="left">目的地</div>
                        <div class="right"><span>{{ detail.mainInfo.signedat }}</span></div>
                    </div>
                    <div class="row">
                        <div class="left">柜数</div>
                        <div class="right"><span class="red-font">{{ sumList.totalPackage }}</span></div>
                    </div>
                    <div class="row">
                        <div class="left">件数</div>
                        <div class="right"><span><span class="red-font">{{ sumList.number }}</span></span></div>
                    </div>
                    <div class="row">
                        <div class="left">重量(KG）</div>
                        <div class="right"><span><span class="red-font">{{ sumList.weight }}</span></span></div>
                    </div>
                    <div class="row">
                        <div class="left">备注</div>
                        <div class="right"><span><span>{{ detail.mainInfo.remark || '无' }}</span></span></div>
                    </div>
                </div>
                <!-- 地址信息 -->
                <div v-if="detail.mainInfo.deliverytype === '0' && detail.addressList.length">
                    <div class="box-title"><span class="left">地址信息</span></div>
                    <div class="common-box" v-for="item in detail.addressList" :key="item.id">
                        <div class="row-addrss">
                            <div class="person-info">
                                <div class="left"><img src="@/assets/images/person_icon.png"></div>
                                <div class="right">
                                    <span class="name">{{ item.contactName }}</span>
                                    <span class="phone">{{ item.contactPhone }}</span>
                                </div>
                            </div>
                            <div class="address">{{ item.province }}{{ item.city }}{{ item.area }}{{ item.address }}</div>
                            <div class="line-solid"></div>
                            <div class="remark-box">
                                <div class="title">送货说明</div>
                                <div class="remark">{{ item.remark ? item.remark : '无' }}</div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 货柜信息 -->
                <div v-if="detail.list.length">
                    <div class="box-title">
                        <span class="left">货物信息</span>
                        <span class="right"><span style="color: #274ED3;">{{ detail.tabIndex + 1 }}</span>/<span>{{
                            detail.list.length }}</span></span>
                    </div>
                    <div class="common-box" style="padding: 0;">
                        <div class="tabs-box">
                            <div style="text-align: left;color: #7e7e7e;">货柜</div>
                            <van-tabs v-model:active="detail.tabIndex" swipeable swipe-threshold="2" color="#1580E5"
                                title-active-color="#1580E5" line-width="100">
                                <van-tab v-for="(item, index) in detail.list" :key="item.id" :title="item.containerno">
                                    <div class="item-box">
                                        <div class="row">
                                            <div class="left">品牌</div>
                                            <div class="right"><span>{{ item.brand || '--' }}</span></div>
                                        </div>
                                        <div class="row">
                                            <div class="left">规格</div>
                                            <div class="right"><span>{{ item.spec || '--' }}</span></div>
                                        </div>
                                        <div class="row">
                                            <div class="left">件数</div>
                                            <div class="right"><span>{{ item.number }}</span></div>
                                        </div>
                                        <div class="row">
                                            <div class="left">重量（KG）</div>
                                            <div class="right"><span>{{ item.weight }}</span></div>
                                        </div>
                                        <div class="row">
                                            <div class="left">件重（KG）</div>
                                            <div class="right"><span>{{ item.unitweight }}</span></div>
                                        </div>
                                        <div class="row">
                                            <div class="left">目的港</div>
                                            <div class="right"><span>{{ item.portname }}</span></div>
                                        </div>
                                        <div class="row"
                                            v-if="detail.mainInfo.status === '1' && detail.mainInfo.deliverytype === '1'">
                                            <div class="left">入库计划</div>
                                            <div class="right">
                                                <span v-if="item.spckmc && item.ssrqid">
                                                    <span>{{ item.spckmc }}</span>
                                                    <span style="margin-left: 20px;">{{ item.ssrqid }}</span>
                                                </span>
                                                <span v-else class="red-font">待安排</span>
                                            </div>
                                        </div>
                                        <div class="row" v-if="detail.mainInfo.status === '1'">
                                            <div class="left">车辆信息</div>
                                            <div class="right">
                                                <span v-if="item.dzzy6 && item.dzzy7">
                                                    <span style="margin-right: 10px;">{{ item.dzzy6 }}</span>
                                                    <span style="margin-right: 10px;">{{ item.dzzy7 }}</span>
                                                    <a v-if="item.dzzy8" :href="`tel:${item.dzzy8}`"
                                                        style=" color: #2386E3;">{{ item.dzzy8 }}</a>
                                                </span>
                                                <span v-else class="red-font">待安排</span>
                                            </div>
                                        </div>
                                    </div>
                                </van-tab>
                            </van-tabs>
                        </div>
                        <div class="tabs-bottom-btn" v-if="isShowWarehouseInArrangeBtn"
                            v-hasPermi="['delivery:warehousing:arrangements']"
                            @click="clickWarehouseInArrange(detail.tabIndex)">
                            <img src="@/assets/images/edit_icon_02.png">
                            录入仓库信息
                        </div>
                        <div class="tabs-bottom-btn" v-if="isShowCarArrangeBtn"
                            v-hasPermi="['delivery:vehicle:arrangement']" @click="clickCarArrange(detail.tabIndex)">
                            <img src="@/assets/images/edit_icon_02.png">
                            录入车辆信息
                        </div>
                    </div>
                </div>
                <!-- 待审 -->
                <van-field v-model="detail.mainInfo.finalcause" v-if="detail.mainInfo.status === '0'" rows="2" autosize
                    label="审批说明" type="textarea" maxlength="300" style="border-radius: 12px;" placeholder="请输入审批说明"
                    show-word-limit v-hasPermi="['delivery:info:approved', 'delivery:info:reject']" />

                <div class="btn-box">
                    <!-- 待审 -->
                    <div v-if="detail.mainInfo.status === '0'">
                        <div class="btn btn1" @click="handleAudit" v-hasPermi="['delivery:info:approved']">审核通过</div>
                        <div class="btn btn2" @click="handleReject" v-hasPermi="['delivery:info:reject']">驳回</div>
                    </div>
                    <!-- 已审 -->
                    <div v-if="detail.mainInfo.status === '1'">
                        <div class="btn btn1" @click="clickSubmitWarehouseInArrange"
                            v-hasPermi="['delivery:warehousing:arrangements']" v-if="isShowWarehouseInArrangeBtn">提交入仓安排
                        </div>
                        <div class="btn btn1" @click="clickSubmitCarArrange" v-hasPermi="['delivery:vehicle:arrangement']"
                            v-if="isShowCarArrangeBtn">提交车辆安排</div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, computed } from 'vue'
import { useRoute } from 'vue-router'
import { msgError, msgSuccess, msgConfirm } from '@/utils/message'
import { setToken, setExpiresIn, getOpenId, setOpenId } from '@/utils/auth'
import { h5login, getUsersByOpenId, getOpenIdByCode, getConfigKey, systemUserGetInfo } from '@/api/staffUser'
import { setLocalStorage, getLocalStorage } from '@/utils/localStorage'
import { mallDeliveryInfoDetails, mallDeliveryInfoApproved, mallDeliveryInfoReject, mallDeliveryInfoVehicleArrangement, mallDeliveryInfoWarehousingArrangements } from '@/api/deliveryManage'
import { WEIGHT_DIGIT, NUMBER_DIGIT, AMOUNT_DIGIT } from '@/utils/constant'
import { delayCloseWindow, priceFormat } from '@/utils/util'
import router from '@/router'
import { useUserInfoStore } from '@/store/userInfo'

const route = useRoute();
const detail: any = reactive({
    id: route.query.id || '',
    loading: false,
    mainInfo: {
        shopid: '',
        ownerid: '',
        portname: '',
        plandate: '',
        deliverytype: '',
        signedat: '',
        remark: '',
        status: '',// 状态 0：待审 1：已审 2：驳回
        finalcause: '',// 审核说明
        node: ''// 安排状态 0:待入仓安排 1：已入仓安排，待车辆安排 2：已入仓安排，已车辆安排 3：全部完成
    },
    addressList: [],
    list: [],
    tabIndex: 0
})

let showPage: any = ref(0);
const configKeyParam: string = 'GZH_APP_ID'
let wxAppid: string = ''
const code: any = route.query.code;
//是否已调用微信返回的code,如果调用wxCode则为1，否则为0
const wxCode: number = getLocalStorage('wxCode') == 1 ? 1 : 0;
const openId: any = getOpenId();
const staffUserListData: any = reactive({
    list: []
})

onMounted(() => {
    if (openId) {
        getUsersOpenId(openId);
    } else {
        if (code) {
            if (wxCode == 0) {
                const href = window.location.href.split('?')[0]
                return configKey(href)
            }
            if (wxCode == 1) {
                setLocalStorage('wxCode', 0)
                return openIdByCode(code)
            }
        } else {
            configKey(window.location.href)
        }
    }
})

function configKey(redirectUri: string) {
    getConfigKey(configKeyParam).then((res: any) => {
        wxAppid = res.msg;
        getCode(redirectUri);
    })
}
function getCode(redirectUri: string) {
    setLocalStorage('wxCode', 1)
    let param = "appid=" + wxAppid + "&redirect_uri=" + redirectUri + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect" + "&id=" + route.query.id;
    let url = "https://open.weixin.qq.com/connect/oauth2/authorize?" + param;
    window.location.href = url
}

function openIdByCode(code: string) {
    getOpenIdByCode({ code: code }).then((res: any) => {
        const openId: string = res.msg;
        setOpenId(openId);
        getUsersOpenId(openId);
    })
}

function getUsersOpenId(openId: string) {
    getUsersByOpenId({ openId: openId }).then((res: any) => {
        const data = res.data;
        staffUserListData.list = data;
        if (data && data.length == 0) {
            return showPage.value = 1;
        }
        if (data && data.length == 1) {
            login(0)
        }
        if (data && data.length > 1) {
            return showPage.value = 2;
        }
    })
}

function login(index: number) {
    const data: any = staffUserListData.list
    h5login({ username: data[index].userName, password: data[index].password }).then((res: any) => {
        const data1 = res.data;
        setToken(data1.access_token);
        setExpiresIn(data1.expires_in);
        getUserInfo();
    })
}

function getUserInfo() {
    detail.loading = true;
    const userInfoStore = useUserInfoStore();
    systemUserGetInfo().then((res: any) => {
        userInfoStore.permissions = res.permissions;
        userInfoStore.roles = res.roles;
        getDetail();
    })
}

function getDetail() {
    mallDeliveryInfoDetails(detail.id).then((res: any) => {
        showPage.value = 3;
        detail.mainInfo = res.data.deliveryInfo;
        detail.list = res.data.deliveryDtRos || [];
        detail.addressList = res.data.deliveryAddressList || [];
        detail.loading = false;
    })
}

function handleAudit() {
    let data = {
        id: detail.id,
        finalcause: detail.mainInfo.finalcause
    }
    msgConfirm("是否确认此操作？").then(() => {
        mallDeliveryInfoApproved(data).then(() => {
            msgSuccess('审核通过');
            delayCloseWindow();
        })
    })
}

function handleReject() {
    if (!detail.mainInfo.finalcause) return msgError('请输入驳回原因！');
    let data = {
        id: detail.id,
        finalcause: detail.mainInfo.finalcause
    }
    msgConfirm("是否确认此操作？").then(() => {
        mallDeliveryInfoReject(data).then(() => {
            msgSuccess('已驳回');
            delayCloseWindow();
        })
    })
}

const sumList = computed(() => {
    const list = detail.list;
    let number = 0;
    let weight = 0;
    let totalAmount = 0;
    list.forEach((item: any) => {
        number += Number(item.number);
        weight += Number(item.weight);
        totalAmount += item.totalAmount ? Number(item.totalAmount) : 0;
    })
    return {
        totalPackage: list.length,
        number: priceFormat(Number(number.toFixed(NUMBER_DIGIT))),
        weight: priceFormat(Number(weight.toFixed(WEIGHT_DIGIT))),
        totalAmount: priceFormat(Number(totalAmount.toFixed(AMOUNT_DIGIT)))
    }
})

const isShowWarehouseInArrangeBtn = computed(() => {
    if (detail.mainInfo.status === '1' && detail.mainInfo.deliverytype === '1' && detail.mainInfo.node === '0') {
        return true;
    } else {
        return false;
    }
})

const isShowCarArrangeBtn = computed(() => {
    if (detail.mainInfo.status == 1) {
        if (detail.mainInfo.deliverytype == 1) {
            if (detail.mainInfo.node == 1) {
                return true;
            } else {
                return false;
            }
        } else {
            return true;
        }
    } else {
        return false;
    }
})

function clickWarehouseInArrange(i: number) {
    const info = detail.list[i];
    const warehouseInfo = {
        id: info.id,
        packageid: info.packageid,
        containerno: info.containerno,
        spckid: info.spckid,
        spckmc: info.spckmc,
        ssrqid: info.ssrqid,
        dzbz: info.dzbz
    }
    setLocalStorage('warehouseInArrangeInfo', warehouseInfo);
    router.push({ name: 'DeliveryWarehouseInArrange' });
}

function clickCarArrange(i: number) {
    const info = detail.list[i];
    const carInfo = {
        id: info.id,
        packageid: info.packageid,
        containerno: info.containerno,
        realitydate: info.realitydate || '',
        dzzy6: info.dzzy6 || '',
        dzzy7: info.dzzy7 || '',
        dzzy8: info.dzzy8 || '',
        dzzy10: info.dzzy10 || '',
        deliverycause: info.deliverycause || '',
    }
    router.push({ name: 'DeliveryCarArrange', query: { ...carInfo } });
}

function clickSubmitWarehouseInArrange() {
    const containernoList = detail.list.filter((item: any) => !item.spckid || !item.ssrqid)
    if (containernoList.length) {
        const tip = containernoList.map((item: any) => item.containerno).join(',');
        return msgError('柜号' + tip + ' 入仓信息未安排');
    }
    msgConfirm("是否确认此操作？").then(() => {
        mallDeliveryInfoWarehousingArrangements({ id: detail.id }).then(() => {
            msgSuccess('提交入仓安排成功');
            delayCloseWindow();
        })
    })
}

function clickSubmitCarArrange() {
    const containernoList = detail.list.filter((item: any) => !item.realitydate || !item.dzzy6 || !item.dzzy7)
    if (containernoList.length) {
        const tip = containernoList.map((item: any) => item.containerno).join(',');
        return msgError('柜号' + tip + ' 车辆信息未安排');
    }
    msgConfirm("是否确认此操作？").then(() => {
        mallDeliveryInfoVehicleArrangement({ id: detail.id }).then(() => {
            msgSuccess('提交车辆安排成功');
            delayCloseWindow();
        })
    })
}
</script>

<style lang="scss" scoped>
div,
span {
    box-sizing: border-box;
}

.empty,
.unbound-tip {
    width: 100%;
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    text-align: center;
}

.box-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: 500;

    .left {
        font-size: 32px;
        color: #000000;
    }

    .right {
        font-size: 30px;

    }
}

.common-box {
    margin: 30px 0;
    padding: 40px 40px;
    background-color: #fff;
    border-radius: 32px;
    position: relative;

    .tag {
        width: 139px;
        height: 54px;
        line-height: 50px;
        text-align: center;
        border-radius: 0px 32px 0px 32px;
        font-size: 28px;
        font-weight: 500;
        position: absolute;
        top: 0;
        right: 0;
    }

    .tag-0 {
        color: #FFFFFF;
        background: linear-gradient(180deg, #E18D14 0%, #EA9E2E 100%);
    }

    .tag-1 {
        color: #FFFFFF;
        background: linear-gradient(180deg, #13AB0D 0%, #24AF0A 100%);
    }

    .row {
        font-size: 30px;
        display: flex;

        &:not(:last-child) {
            margin-bottom: 16px;

        }

        .left {
            width: 170px;
            color: #7e7e7e;
        }

        .right {
            color: #000000;

            .red-font {
                color: #D3625D;
            }
        }
    }

    .item-box {
        margin-top: 30px;
    }
}

.delivery-detail {
    width: 100%;
    background-color: #F2F2F2;
    min-height: 100vh;

    .delivery-detail-container {
        padding: 0 24px 24px 24px;
        width: 100%;

        .row-top {
            display: flex;

            .left {
                img {
                    width: 72px;
                    height: 72px;
                }
            }

            .right {
                margin-left: 20px;
                display: flex;
                flex-direction: column;

                .text {
                    font-size: 26px;
                    color: #7e7e7e;
                }
            }
        }

        .line {
            margin: 20px 0 30px;
            height: 2px;
            border: 2px dashed #E7DADA;
        }

        .row-addrss {
            font-size: 30px;

            .person-info {
                display: flex;

                .left {
                    img {
                        width: 78px;
                        height: 78px;
                    }
                }

                .right {
                    margin-left: 20px;
                    display: flex;
                    flex-direction: column;
                    justify-content: space-between;

                    .name {
                        font-weight: 600;
                    }
                }
            }

            .address {
                margin: 26px 0;
            }

            .line-solid {
                margin: 26px 0;
                border-bottom: 2px solid #F2F2F2;
            }

            .remark-box {
                font-size: 30px;

                .title {
                    margin-bottom: 16px;
                    color: #7e7e7e;
                }

                .remark {
                    color: #000000
                }
            }
        }

        .tabs-box {
            padding: 40px 40px;
            padding-top: 20px !important;
            position: relative;
            overflow: hidden;
        }

        .tabs-bottom-btn {
            width: 100%;
            height: 96px;
            background: #F6FBFF;
            border-bottom-left-radius: 32px;
            border-bottom-right-radius: 32px;
            font-size: 32px;
            font-family: PingFangSC, PingFang SC;
            color: #2386E3;
            display: flex;
            align-items: center;
            justify-content: center;

            img {
                margin-right: 10px;
                width: 32px;
                height: 32px;
            }
        }

        .btn-box {
            margin-top: 44px;

            .btn {
                margin: 24px auto 0;
                width: 700px;
                height: 96px;
                line-height: 96px;
                text-align: center;
                border-radius: 24px;
            }

            .btn1 {
                color: #FFFFFF;
                background: #2386E3;
            }

            .btn2 {
                color: #333333;
                background: #FFFFFF;
                border: 2rpx solid #DDDDDD;
            }
        }
    }
}
</style>